#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2023/8/21 8:19
# @Author  : jiangwei
# @Site    : 
# @File    : login_shein_driss.py
# @Software: PyCharm
import sys
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

import time
import json
from datetime import datetime
from DrissionPage import ChromiumPage
from pipeline.sql_connect import WaicangSqlConnect
from utils.send_feishu import send_notice
from common.config import shein_login


def check_logon_success(page, wc, shop):
    """
    校验登录是否成功
    :param page:
    :return:
    """
    current_url = page.url
    print(current_url)

    login_ele = page.eles("xpath://input[@name='username']")
    if len(login_ele) == 0 or "login" not in current_url:
        print("已经是在登录后的主页页面")
        cookies = page.cookies
        print(cookies)
        update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # save_key_redis(name="shein", key="shein_goods", cookie=json.dumps(cookies, ensure_ascii=False))
        if not wc:
            wc = WaicangSqlConnect()
        wc.save_temu_seller_cookie(cookies=json.dumps(cookies, ensure_ascii=False), update_time=update_time,
                                   platform_name="shein_seller_{}".format(shop))
        return True

    return False


# 创建默认的窗口对象
def login_shein_driss(shop="US_SN1_CB"):
    """
    登录猛犸
    """
    page = ChromiumPage()
    wc = WaicangSqlConnect()
    cookies = {}

    success_png_path = "./login_shein_driss.png"
    failed_png_path = "./login_shein_failed.png"
    if os.path.exists(success_png_path):
        os.remove(success_png_path)

    if os.path.exists(failed_png_path):
        os.remove(failed_png_path)

    try:
        page.get("https://sso.geiwohuo.com/#/home")
        time.sleep(3)
        page.refresh()
        url_now = page.url
        print(url_now)
        # if check_logon_success(page=page, wc=wc):
        #     cookies = page.cookies
        #     if page.tabs:
        #         page.close_other_tabs()
        #         page.close_tabs()
        #     wc.close()
        #     return cookies

        old_cookies = wc.query_temu_seller_cookie(platform_name="shein_seller_{}".format(shop))
        if old_cookies:
            ck = json.loads(old_cookies)
            print(ck)
            page.set.cookies(ck)
            print("cookie更新")
            page.get("https://sso.geiwohuo.com/#/home")
            time.sleep(1)
            if check_logon_success(page=page, wc=wc, shop=shop):
                print("旧cookie登录成功")
                cookies = page.cookies
                if page.tabs:
                    page.close_other_tabs()
                    page.close_tabs()
                wc.close()
                return cookies
        # 一店旧帐号，还可以用，暂时不换
        # 账号：S18125085
        # 密码：Miniso2023!

        # 店铺一店用US_SN1_CB，二店用US_SN2_CB，三店用US_SN3_CB， 四店用US_SN4_CB
        # Shein一店	S13716159	Miniso2023!  验证码唐璀
        # Shein二店	GS4325263	Miniso2024!  验证码唐璀
        # Shein三店	GS6281473	Minisolife2025  2025年3月17号新增两个店铺
        # Shein四店	GS4432510	HappyMiniso2025

        # user = "S18125085" if shop == "US_SN1_CB" else "GS4325263"
        # pwd = "Miniso2023!" if shop == "US_SN1_CB" else "Miniso2024!"
        user = shein_login.get(shop).get('user')
        pwd = shein_login.get(shop).get('pwd')
        time.sleep(1)
        login_url = "https://sso.geiwohuo.com/#/login/GMPSSO/aHR0cHM6Ly9zc28uZ2Vpd29odW8uY29tLyMvaG9tZQ=="
        page.get(login_url)
        url_now = page.url
        print(url_now)

        # 1 输入账号
        page.eles("xpath://input[@name='username']")[0].input(user)
        time.sleep(1)
        print("【输入账号：{}】成功".format(user))

        # 2 输入密码
        page.eles("xpath://input[@name='password']")[0].input(pwd)
        time.sleep(1)
        print("【输入密码:{}】成功".format(pwd))

        # 3 点击登录
        button_ele = page.eles("xpath://button[@class='so-button so-button-default style__login_btn--nwCyS5Yt']")
        button_ele[0].click()
        print("【点击登录】成功")
        time.sleep(3)

        time.sleep(100)  #手动输入验证码

        page.refresh()
        url_now = page.url

        print("--当前URL--", url_now)
        time.sleep(10)

        # 4 手机验证码  【首次登录有手机验证码】
        phone_verify = page.eles("#verifyCode")
        if phone_verify:
            print("出来了手机验证码，请联系业务获取后再登录")
            page.get_screenshot(failed_png_path)
            time.sleep(300)
            # send_user(content="shein 登录出来手机验证码异常，请开发联系相关同事处理，谢谢！")
            send_notice(content="shein 登录{}出来手机验证码异常，请开发联系相关同事处理，谢谢！".format(shop))
            if page.tabs:
                page.close_other_tabs()
                page.close_tabs()
            print("程序运行结束")
            wc.close()
            return {}

        else:
            cookies = page.cookies
            print(cookies)
            # save_key_redis(name="temu", key="temu_shop", cookie=json.dumps(cookies, ensure_ascii=False))
            update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            wc.save_temu_seller_cookie(cookies=json.dumps(cookies, ensure_ascii=False), update_time=update_time,
                                       platform_name="shein_seller_{}".format(shop))
            if page.tabs:
                page.close_other_tabs()
                page.close_tabs()
            print("程序运行结束")
            wc.close()
            return cookies

    except Exception as e:
        page.get_screenshot(failed_png_path)
        print(e)
        print("执行登录异常")
        if page.tabs:
            page.close_other_tabs()
            page.close_tabs()
        print("程序运行结束")
        return {}


if __name__ == '__main__':
    #     shop = "US_SN1_CB"
    #     cookies = {
    #     '_ga': 'GA1.1.2052503400.1731285727',
    #     'gmp_trace': 'cb29c58be67b485da786e4659d20b28d',
    #     'accept-language': 'CN',
    #     'ssoEnvDevice': 'pc',
    #     'SITE_ID': '5f1edd52-9787-4d7e-b439-b8e6407a690d',
    #     'armorUuid': '20241206180102fdc72f52fb0f32131d7cb5e983fd568300ffcbf361d24a0100',
    #     'pfmp_trace': '7962696dc64e42438ef6019adea118e0',
    #     'issso': '1',
    #     'sso_login_trace': '20241115085758-d713be5bddab45bcaa3cd131e220f4cc',
    #     'c': '3OlVKBfU-1692577151375-7031474d2dd8b-1973685867',
    #     'smidV2': '20241206180102715a2c59b4968d0c095f24c23de6bc70009e0ff8e722772c0',
    #     '_ga_SJ3CWCK1VV': 'GS1.1.1734935872.54.0.1734935872.0.0.0',
    #     '_ga_BY7EZRXJL2': 'GS1.1.1734935872.53.1.1734935934.0.0.0',
    #     }
    #
    #     shop = "US_SN2_CB"
    #     cookies = {
    #     'gmp_trace': '850626c194024190a2e85bf9502c329a',
    #     'accept-language': 'CN',
    #     'ssoEnvDevice': 'pc',
    #     'armorUuid': '20241223140349722e11eab152915d9bfeea012475a9f300438da01522aded00',
    #     '_ga': 'GA1.1.622320273.1734933830',
    #     'smidV2': '20241223140349b81a5028722c3b21760824bb163faf2e00219c97fc9949d80',
    #     'SITE_ID': 'c7138725-b34e-45d4-9e46-5f8540ca7d0f',
    #     'issso': '1',
    #     'sso_login_trace': '20241223141837-c8090eb37580450ea7086f2bdc800512',
    #     '_ga_BY7EZRXJL2': 'GS1.1.1734933829.1.1.1734936214.0.0.0',
    #     '_ga_SJ3CWCK1VV': 'GS1.1.1734934721.1.1.1734936214.0.0.0',
    # }

    # wc = WaicangSqlConnect()
    # update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # wc.save_temu_seller_cookie(cookies=json.dumps(cookies, ensure_ascii=False), update_time=update_time,
    #                            platform_name="shein_seller_{}".format(shop))
    # wc.close()

    # 店铺一店用US_SN1_CB，二店用US_SN2_CB
    # Shein一店	S13716159	Miniso2023!  验证码唐璀
    # Shein二店	GS4325263	Miniso2024!  验证码唐璀
    # Shein三店	GS6281473	Minisolife2025  2025年3月17号新增两个店铺
    # Shein四店	GS4432510	HappyMiniso2025
    # ["US_SN1_CB", "US_SN2_CB", "US_SN3_CB", "US_SN4_CB"]
    shop = "US_SN2_CB"
    login_shein_driss(shop=shop)
